package com.duduso.gerador.screens;

import com.duduso.gerador.comum.LimitaTextoNumerico;
import com.duduso.gerador.comum.MonetarioDocument;
import com.duduso.gerador.comum.LimitaTexto;
import com.duduso.gerador.comum.SelecaoArquivo;
import com.duduso.gerador.dto.Rifa;
import com.duduso.gerador.util.Mensagens;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import javax.swing.plaf.metal.MetalButtonUI;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author duduso
 */
public class FormularioPrincipal extends javax.swing.JFrame {
    
    private String caminhoArquivoSelecionado;
    
    /**
     * Creates new form FormularioPrincipal
     */
    public FormularioPrincipal() {
        initComponents();
        setLocationRelativeTo(null);  
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        lbTitulo = new javax.swing.JLabel();
        tfTitulo = new javax.swing.JTextField(new LimitaTexto(50), "", 10);
        lbDescricao = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        taDescricao = new javax.swing.JTextArea(new LimitaTexto(250));
        lbQtdRifas = new javax.swing.JLabel();
        tfQtdRifas = new javax.swing.JTextField(new LimitaTextoNumerico(5), "", 10);
        btGerarEtiquetas = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        tfValorRifa = new javax.swing.JTextField();
        lbImagem = new javax.swing.JLabel();
        tfArquivoSelecionado = new javax.swing.JTextField();
        btSelecionarArquivo = new javax.swing.JButton();
        btLimpar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        lbGeradorBloquetosRifas = new javax.swing.JLabel();

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane2.setViewportView(jTextArea1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Bloquetos JAVA");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED), "Dados Para Geração dos Bloquetos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Calibri", 1, 14))); // NOI18N

        lbTitulo.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        lbTitulo.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbTitulo.setText("Título: *");

        tfTitulo.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        tfTitulo.setToolTipText("Informe o Título do Bloqueto (Máx.: 50 Caracteres)");
        tfTitulo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfTituloActionPerformed(evt);
            }
        });

        lbDescricao.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        lbDescricao.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbDescricao.setText("Descrição: *");

        taDescricao.setColumns(20);
        taDescricao.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        taDescricao.setLineWrap(true);
        taDescricao.setRows(3);
        taDescricao.setToolTipText("Informe a Descrição do Produto a Ser Rifado (Máx.: 250 caracteres)");
        jScrollPane1.setViewportView(taDescricao);

        lbQtdRifas.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        lbQtdRifas.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbQtdRifas.setText("Qtd. Rifas: *");

        tfQtdRifas.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        tfQtdRifas.setToolTipText("Quantidade de Rifas a Serem Geradas (Máx.: 99.999)");
        tfQtdRifas.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));

        btGerarEtiquetas.setUI(new MetalButtonUI());
        btGerarEtiquetas.setContentAreaFilled(false);
        btGerarEtiquetas.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
        btGerarEtiquetas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ok.png"))); // NOI18N
        btGerarEtiquetas.setText("Gerar Etiquetas");
        btGerarEtiquetas.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btGerarEtiquetas.setFocusPainted(false);
        btGerarEtiquetas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btGerarEtiquetasActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel1.setText("Valor Rifa: *");

        tfValorRifa.setFont(new java.awt.Font("Calibri", 0, 13));
        tfValorRifa.setToolTipText("Valor de Cada Rifa (Em Reais)");
        tfValorRifa.setDocument(new MonetarioDocument());

        lbImagem.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        lbImagem.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbImagem.setText("Imagem:   ");

        tfArquivoSelecionado.setEditable(false);
        tfArquivoSelecionado.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        tfArquivoSelecionado.setEnabled(false);
        tfArquivoSelecionado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfArquivoSelecionadoActionPerformed(evt);
            }
        });

        btSelecionarArquivo.setContentAreaFilled(false);
        btSelecionarArquivo.setUI(new MetalButtonUI());
        btSelecionarArquivo.setFont(new java.awt.Font("Calibri", 1, 13)); // NOI18N
        btSelecionarArquivo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/find.png"))); // NOI18N
        btSelecionarArquivo.setText("Selecionar Imagem");
        btSelecionarArquivo.setFocusPainted(false);
        btSelecionarArquivo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSelecionarArquivoActionPerformed(evt);
            }
        });

        btLimpar.setContentAreaFilled(false);
        btLimpar.setUI(new MetalButtonUI());
        btLimpar.setFont(new java.awt.Font("Calibri", 1, 13)); // NOI18N
        btLimpar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clear.png"))); // NOI18N
        btLimpar.setText("Limpar");
        btLimpar.setFocusPainted(false);
        btLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLimparActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lbImagem, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
                    .addComponent(lbQtdRifas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lbDescricao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lbTitulo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(14, 14, 14)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tfTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(tfValorRifa, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)
                        .addComponent(tfQtdRifas, javax.swing.GroupLayout.Alignment.LEADING))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(tfArquivoSelecionado, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btSelecionarArquivo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(230, 230, 230)
                .addComponent(btGerarEtiquetas)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbTitulo)
                    .addComponent(tfTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbDescricao)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(16, 16, 16)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbQtdRifas)
                    .addComponent(tfQtdRifas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tfValorRifa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbImagem)
                    .addComponent(tfArquivoSelecionado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btSelecionarArquivo)
                    .addComponent(btLimpar))
                .addGap(29, 29, 29)
                .addComponent(btGerarEtiquetas)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));

        lbGeradorBloquetosRifas.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N
        lbGeradorBloquetosRifas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/contacts.png"))); // NOI18N
        lbGeradorBloquetosRifas.setText("Gerador de Bloquetos de Rifas");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbGeradorBloquetosRifas, javax.swing.GroupLayout.DEFAULT_SIZE, 657, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lbGeradorBloquetosRifas, javax.swing.GroupLayout.DEFAULT_SIZE, 59, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tfTituloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfTituloActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfTituloActionPerformed

    private void btGerarEtiquetasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btGerarEtiquetasActionPerformed
        gerarEtiquetas();
    }//GEN-LAST:event_btGerarEtiquetasActionPerformed

    private void tfArquivoSelecionadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfArquivoSelecionadoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfArquivoSelecionadoActionPerformed

    private void btSelecionarArquivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSelecionarArquivoActionPerformed
        selecionarArquivo();
    }//GEN-LAST:event_btSelecionarArquivoActionPerformed

    private void btLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLimparActionPerformed
        this.caminhoArquivoSelecionado = null;
        this.tfArquivoSelecionado.setText(null);
    }//GEN-LAST:event_btLimparActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormularioPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormularioPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormularioPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormularioPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormularioPrincipal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btGerarEtiquetas;
    private javax.swing.JButton btLimpar;
    private javax.swing.JButton btSelecionarArquivo;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JLabel lbDescricao;
    private javax.swing.JLabel lbGeradorBloquetosRifas;
    private javax.swing.JLabel lbImagem;
    private javax.swing.JLabel lbQtdRifas;
    private javax.swing.JLabel lbTitulo;
    private javax.swing.JTextArea taDescricao;
    private javax.swing.JTextField tfArquivoSelecionado;
    private javax.swing.JTextField tfQtdRifas;
    private javax.swing.JTextField tfTitulo;
    private javax.swing.JTextField tfValorRifa;
    // End of variables declaration//GEN-END:variables

    private void gerarEtiquetas(){
        
        String titulo = this.tfTitulo.getText();
        String descricao = this.taDescricao.getText();
        String qtdRifas = this.tfQtdRifas.getText();
        String valorRifa = this.tfValorRifa.getText();
        
        if(campoNaoPreenchido(titulo)){
            Mensagens.getInstance().exibirMensagemErro(null, "existem_campos_obrigatorios_nao_preenchidos");
            return;
        }
        
        if(campoNaoPreenchido(descricao)){
            Mensagens.getInstance().exibirMensagemErro(null, "existem_campos_obrigatorios_nao_preenchidos");
            return;
        }
        
        if(campoNaoPreenchido(qtdRifas)){
            Mensagens.getInstance().exibirMensagemErro(null, "existem_campos_obrigatorios_nao_preenchidos");
            return;
        }
        
        if(campoNaoPreenchido(valorRifa)){
            Mensagens.getInstance().exibirMensagemErro(null, "existem_campos_obrigatorios_nao_preenchidos");
            return;
        }
        
        ArrayList<Rifa> rifas = new ArrayList<Rifa>();
        Integer totalRifas = Integer.valueOf(qtdRifas);
        
        for(int i = 0; i < totalRifas; i++){
            
            Rifa rifa = new Rifa();
            rifa.setTitulo(titulo);
            rifa.setDescricao(descricao);
            rifa.setValor(valorRifa);
            rifa.setSequencial(String.format("%05d", (i + 1)));
            rifa.setImagem(this.caminhoArquivoSelecionado);
            rifas.add(rifa);
            
        }
        
        try {
            
            InputStream stream = getClass().getResourceAsStream(Mensagens.getInstance().getMessage("caminho_relatorio"));
            JasperPrint impressao = JasperFillManager.fillReport(stream, null, new JRBeanCollectionDataSource(rifas));  
            JasperViewer viewer = new JasperViewer(impressao, false);  
            viewer.setTitle(Mensagens.getInstance().getMessage("rifas_geradas"));  
            viewer.show();          
            
        } catch (Exception e) {
            
            Mensagens.getInstance().exibirMensagemErro(null, e.getMessage());
            
        }
        
    }
    
    public void selecionarArquivo(){
        
        File arquivo = SelecaoArquivo.getInstance(".png").selecionarArquivo();
        
        if(arquivo != null){
            this.tfArquivoSelecionado.setText(arquivo.getName());
            this.caminhoArquivoSelecionado = arquivo.getAbsolutePath();
        }
        
    }
    
    private boolean campoNaoPreenchido(String value){
        return value == null || value.isEmpty();
    }
    
}
